﻿package pcenshao.commons.simpledb.mssql;

import java.util.List;

import javax.sql.DataSource;

import pcenshao.commons.simpledb.BasicEntityManager;
import pcenshao.commons.simpledb.Entity;


/**
 * 使用queryRange时,将在Entity中设置一个属性row_num,表示ROW_NUMBER()函数的结果
 * 
 * @author pengyw
 * 
 */
public class MsSqlEntityManager extends BasicEntityManager {

	public MsSqlEntityManager() {
		super();
	}

	public MsSqlEntityManager(DataSource dataSource, boolean lazyInit) {
		super(dataSource, lazyInit);
	}

	public MsSqlEntityManager(DataSource dataSource) {
		super(dataSource);
	}

	private String orderByColumn;

	/**
	 * queryRange需要使用的排序的字段
	 * 
	 * @return
	 */
	public String getOrderByColumn() {
		return orderByColumn;
	}

	public void setOrderByColumn(String orderByColumn) {
		this.orderByColumn = orderByColumn;
	}

	/**
	 * 查询一个区间,分页<br>
	 * 
	 * @param tableName
	 * @param orderByColumn
	 *            排序的列
	 * @param columns
	 *            null,length=0 => select * from
	 * @param where
	 * @param args
	 * @param offset
	 * @param limit
	 * @return Entity将包含一个属性row_num
	 */
	public List<Entity> queryRange(String tableName, String[] columns,
			String where, Object[] args, int offset, int limit) {
		if (tableName == null)
			throw new NullPointerException("tableName=null");
		if (columns == null) {
			columns = new String[] {};
		}

		String orderBy = "CURRENT_TIMESTAMP";
		if (this.orderByColumn != null) {
			orderBy = this.orderByColumn;
		}

		String sql = MsSQLUtil.generate2005PagingSQL(tableName, orderBy, where,
				offset, limit, columns);

		List<Entity> list = queryList(sql, args);
		if (list != null) {
			for (Entity en : list) {
				en.setAttribute("row_num", en.get("___row_num"));
				en.remove("___row_num"); // 移除排序时使用的字段
				en.setTableName(tableName);
			} 
		}
		return list;
	}
}
